package frontend.pages.reports.charismasynch;

import backend.service.charisma.CharismaDataSynchronizer;
import frontend.core.TimeTrackingWebApplication;
import org.apache.wicket.ajax.AbstractAjaxTimerBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.util.time.Duration;

import java.io.Serializable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public abstract class FutureUpdateBehavior<T> extends AbstractAjaxTimerBehavior implements Serializable {

    private transient Future<T> future;

    public FutureUpdateBehavior(Duration updateInterval, Future<T> futureTask) {
        super(updateInterval);
        this.future = futureTask;
    }

    protected abstract void onPostSuccess(AjaxRequestTarget target);

    protected abstract void onUpdateError(AjaxRequestTarget target, Exception e);

    protected void onTimer(final AjaxRequestTarget target){
        if(future.isDone()){
            try{
                T data = future.get();
                getComponent().setDefaultModelObject(data);
                stop();
                onPostSuccess(target);
            }
            catch(InterruptedException e){
                stop();
                String message = "Error occurred while fetching data: "+e.getMessage();
                onUpdateError(target, e);
            }
            catch(ExecutionException e){
                stop();
                String message = "Error occurred while fetching data: "+e.getMessage();
                onUpdateError(target, e);
            }
        }
    }
}
